package org.jasig.cas.client.util;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.spec.KeySpec;

public class DESUtil {

	public DESUtil() {
		//构造函数
	}

	public static String initSecretKey() throws Exception {
		// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
		KeyGenerator kg = KeyGenerator.getInstance("DES");
		// 初始化此密钥生成器，使其具有确定的密钥大小
		kg.init(56);
		// 生成一个密钥
		SecretKey secretKey = kg.generateKey();
		BASE64Encoder b=new BASE64Encoder();
		return String.valueOf(b.encode(secretKey.getEncoded()));
	}

	/**
	 * 解密方法
	 */
	public static String decrypt(String content, String key) throws Exception {
		BASE64Decoder bd64 = new BASE64Decoder();
		byte[] contents = bd64.decodeBuffer(content);
		Cipher cipher = Cipher.getInstance("DES");
		BASE64Decoder b=new BASE64Decoder();
		KeySpec keySpec=new DESKeySpec(b.decodeBuffer(key));
		SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		return new String(cipher.doFinal(contents), "GB2312");
	}

	/**
	 * 加密方法
	 */
	public static String encrypt(String content, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("DES");
		BASE64Decoder b=new BASE64Decoder();
		KeySpec keySpec=new DESKeySpec(b.decodeBuffer(key));
		SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] bytes1 = cipher.doFinal(content.getBytes("GB2312"));// 内容加密
		BASE64Encoder base64 = new BASE64Encoder();
		String enStr = base64.encode(bytes1);
		return enStr;
	}

	public static void main(String[] args) throws Exception {
//		String str = "EVYe8+1BHujKouE1wXzKQJtIJ2Ee5qAh";
//		String pswd = "abc3defghij=";
		//System.out.println(decrypt(str,pswd));
		
	}
}
